<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Pages extends Controller {

	function setVars(){
		$this->tpl['tpljs'][]  = 'title_to_slug';
		$this->tpl['head'] = '';
		$this->tpl['title'] = 'Admins Desk: Add Pages';
		$this->uid = $this->session->userdata('uid');
        $this->slug = $this->uri->segment(4, FALSE);
	}
    
	function __construct()
	{
		parent::Controller();
        $this->auth->CheckTaMeR(101);
		log_message('debug', "Admin: Controler Class Initialized");
		$this->setVars();
	}

	function index()
	{
        $query = $this->getdblist();
        foreach($query->result_array() as $k => $v) {
            $tbresult[$k] = $v;
        }
        $this->load->library('table');
        $this->table->set_heading('slug', 'Title');
        foreach($tbresult as $row){
            $s = $row['slug'];
            $row['slug'] = anchor('admin/pages/add_edit_page/'.$s,$s);
            $this->table->add_row($row);
        }            
        $this->tpl['body'] = $this->table->generate();
        $this->table->clear();
        $this->load->view('blank', $this->tpl);
	}

    
    function add_edit_page()
    {
        $this->load->library('table');
        //$this->load->helper('form');
        $this->getdb();
        extract($this->dbdata);
        if (isset($_POST['submit_page']))
		{
			$this->postCheck();
            extract($this->vdata, EXTR_OVERWRITE);
		}
        
        $attributes = array('name' => 'page');
        $this->tpl['body'] =  form_open("admin/pages/add_edit_page/$this->slug", $attributes);
        if($this->action == 'edit'){
            $js = '';
            $form['Title'] = '<input type="text" name="Title" id="Title" value="'.$Title.'" maxlength="200" size="50" onkeyup="'.$js.'" />';
            $form[1]['slug'] =  '<input type="text" readonly="readonly" name="slug" value="'.$slug.'"/>';
        }elseif($this->action = 'add'){
            $js = "title_to_slug('page', 'Title', 'slug')";
            $form['Title'] = '<input type="text" name="Title" id="PageTitle" value="'.$Title.'" maxlength="200" size="50" onkeyup="'.$js.'" />';
            $form[1]['slug'] =  '<input type="text" name="slug" id="PageSlug" value="'.$slug.'"/>';
        }else{
            log_message('error', "Admin: dbView->pages.php error with action");
        }
        $form[1]['Groups'] =  form_dropdown('Groups', user_groups(), $Groups);
        $form['Typography'] =  form_checkbox('typography', '1', FALSE).'Yes';
        $form['Body'] =  '<textarea name="Body" rows="20" cols="80" />'.$Body.'</textarea>';
        $this->tpl['body'] .= $this->table->form_table($form);
        $this->tpl['body'] .= '<div style="text-align: right;"><input type="submit" name="submit_page" value="Submit" /></div>';
        $this->tpl['body'] .= '</form>';
        $this->load->view('blank', $this->tpl);
    }

	function postCheck()
	{
		$this->load->library('validation');
		$rules['Title']			= 'trim|min_length[5]|max_length[200]';
		$rules['slug']		    = 'trim|min_length[5]|max_length[200]|alpha_dash';
        $rules['Groups']		= 'trim|required|max_length[30]|alpha_dash';
        $rules['Body']  		= 'trim|required|';
        $rules['url']           = 'trim';
        $this->validation->set_rules($rules);
        $val = $this->validation->run();
        $this->vdata = (array) $this->dbdata;
        foreach($this->vdata as $k => $v){
            if(isset($this->validation->$k)){
                $this->vdata[$k] = $this->validation->$k;
            }
        }
		if ($val !== FALSE)
		{
            $this->editdb();
        }
    }
    
    function getdblist()
    {
        $this->db->select('slug, Title');
        $this->db->orderby("slug", "asc");
        $query = $this->db->get('view');
        if($query->num_rows() == 0) {
            redirect('admin/pages/add_edit_page', 'location');
        }else{
            return $query;
        }
    }    
    function getdb()
    {
        if($this->slug !== FALSE){
            $query = $this->db->getwhere('view', array('slug' => $this->slug), 1);
            if($query->num_rows() == 0) {
                redirect('admin/pages/add_edit_page', 'location');
            }else{

                $dbdata = $query->row_array();
                $this->vid = $dbdata['id'];
                $this->dbdata = $dbdata;
                $this->action = 'edit';
                //$this->tpl = array_merge($this->tpl, $this->dbdata);
            }
        }else{
            $fields = $this->db->list_fields('view');
            foreach ($fields as $field) $this->dbdata[$field] = '';
            delids($this->dbdata);
            $this->action = 'add';
            //$this->tpl = array_merge($this->tpl, $this->dbdata);
        }
    }

    function editdb()
    {
        if( ! isset($this->vid) || $this->vid < 1)
        {   # Create if it doesn't excist.
            $slug = $this->vdata['slug'];
            $this->db->insert('view', array('slug' => $slug)); 
            $this->vid = $this->db->insert_id();
        } 
        $data = new_value($this->dbdata, $this->vdata);
        if(count($data) != 0){
            # Make typography Optional: 
            // Add option (Check Box) to use typography to the form field
            if($this->input->post('typography') == '1'){
                $this->load->helper('typography');
                $data['Body'] = auto_typography($data['Body']);
            }
            $this->db->where('id', $this->vid);
            $this->db->update('view', $data);
            $this->msg->setMsg('Your Record has been updated');
        }else{
            $this->msg->setError('Nothing to update');
        }
    }
}
?>
